package com.itheima.easy.security;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.base.AjaxResult;
import com.itheima.easy.enums.BasicEnum;
import com.itheima.easy.utils.AjaxResultBuild;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName RestfulAccessDeniedHandler.java
 * @Description 请求的url超出其权限时异常处理
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter out = response.getWriter();
        AjaxResult<Boolean> responseWrap = AjaxResultBuild.build(BasicEnum.SECURITY_ACCESSDENIED_FAIL, false);
        out.write(JSONObject.toJSONString(responseWrap));
        out.flush();
        out.close();

    }
}

